﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Windows;
using System.Windows.Controls.Primitives;
using System.Linq;
using System.Diagnostics;

namespace MvvmTreeView
{
    public class WindowsStyleTreeViewDragDropTarget : TreeViewDragDropTarget
    {
        private ITreeNode dropTarget;
        private int insertionIndex;

        protected override void OnDrop(Microsoft.Windows.DragEventArgs args)
        {
            var item = this.GetDropTarget(args) as TreeViewItem;

            if (item != null)
            {
                var originalSource = (DependencyObject)args.OriginalSource;
                var ancestor = GetItemsControlAncestor(originalSource);

                insertionIndex = base.GetDropTargetInsertionIndex(ancestor, args);

                dropTarget = (ITreeNode)item.GetItem();
            }
            else
            {
                dropTarget = null;
                insertionIndex = -1;
            }
        }

        public int GetInsertionIndex(ItemDragEventArgs args)
        {
            return insertionIndex;
        }

        public ITreeNode GetDropTargetNode(ItemDragEventArgs args)
        {
            return dropTarget;
        }

        public ITreeNode GetDropTargetNode(Microsoft.Windows.DragEventArgs args)
        {
            var dependencyObject = (DependencyObject)args.OriginalSource;
            var item = dependencyObject.GetVisualAncestors().OfType<TreeViewItem>().FirstOrDefault();
            var item2 = GetDropTarget(args);

            if (item != null)
            {
                var treeNode = (ITreeNode)item.GetItem();

                return treeNode;
            }

            return null;
        }
    }
}
